/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.app.client.form.bindings;

import java.io.Serializable;

import org.nuxeo.gwt.habyt.app.client.form.FormControl;
import org.nuxeo.gwt.habyt.templates.client.bindings.Helper;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.PasswordTextBox;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class PasswordFactory extends AbstractControlFactory {

    public PasswordFactory() {
        super("password");
    }

    @Override
    protected FormControl createControl(Element element) {
        String name = Helper.getAttribute(element, "name");
        String readonly = Helper.getAttribute(element, "readonly");
        String disabled = Helper.getAttribute(element, "disabled");
        String size = Helper.getAttribute(element, "size");
        String maxlength = Helper.getAttribute(element, "maxlength");
        String value = Helper.getAttribute(element, "value");

        PasswordTextBox w = new PasswordTextBox();
        if (name != null) {
            w.setName(name);
        }
        if (readonly != null) {
            w.setReadOnly(Boolean.parseBoolean(readonly));
        }
        if (disabled != null) {
            w.setEnabled(!Boolean.parseBoolean(disabled));
        }
        if (size != null) {
            w.setVisibleLength(Integer.parseInt(size));
        }
        if (maxlength != null) {
            w.setMaxLength(Integer.parseInt(maxlength));
        }
        if (value != null) {
            w.setValue(value);
        }
        return new FormControl(w) {
            @Override
            public String getName() {
                return ((PasswordTextBox) getWidget()).getName();
            }

            @Override
            public Serializable getValue() {
                return ((PasswordTextBox) getWidget()).getValue();
            }

            public void setValue(Serializable value) {
                ((PasswordTextBox) getWidget()).setValue(value == null ? ""
                        : value.toString());
            }
        };
    }

}
